;(function ($,window,document){

    var defaults = {
        title:'请选择设备',
        root:null,//根路径
        multiple:true,
        fileType:null,
        keyId:null,
        keyType:null,
        type:null,
        callback:function(){}   //回调
    };



    this.FileUpload = function (element,options){
        var opts = options;
        $obj = $(element);

        this.FileType = function(){
            var url = opts.root + "/base/queryItem";
            $obj.find("select[name='fileType']").html("");
            publicAjax(url,"POST",{type:opts.fileType},function (data) {
                if(data.ret == 200){
                    var html = "";
                    $.each(data.data,function (index,item){
                        html += "<option value='"+item.itemId+"'>"+item.item+"</option>";
                    });
                    $obj.find("select[name='fileType']").html(html);
                    $obj.find("select[name='fileType']").val(null).trigger("change");
                }else{
                    flavrShowByTime(data.msg,null,"danger",false);
                }
            });
        }

        this.Validator = function(){
            $("#formFile").bootstrapValidator({
                excluded: [':disabled', ':hidden', ':not(:visible)'],
                live: 'enabled',
                message: '非有效值',
                fields: {
                    fileType: {
                        validators: {
                            notEmpty: {
                                message: '文件类型不能为空'
                            }
                        }
                    },
                    files: {
                        validators: {
                            notEmpty: {
                                message: '文件不能为空'
                            }
                        }
                    },
                    fileDateStart:{
                        validators: {
                            date: {
                                format: 'YYYY-MM-DD',
                                message: '格式为YYYY-MM-DD'
                            }
                        }
                    },
                    fileDateEnd:{
                        validators: {
                            date: {
                                format: 'YYYY-MM-DD',
                                message: '格式为YYYY-MM-DD'
                            }
                        }
                    }
                }
            });
        }


        this.filling = function(opts,obj){
            $obj.iziModal({
                title: '上传文件',
                headerColor: '#00c0ef',
                theme: '',  // light
                attached: '', // bottom, top
                icon: null,
                iconText: null,
                iconColor: '',
                rtl: false,
                width: 800,
                padding: 0,
                rtl: false,
                zindex: 1050,
                iframe: false,
                iframeHeight: 400,
                iframeURL: null,
                focusInput: false,
                group: '',
                loop: false,
                navigateCaption: true,
                navigateArrows: true, // closeToModal, closeScreenEdge
                history: true,
                restoreDefaultContent: false,
                autoOpen: true, // Boolean, Number
                bodyOverflow: false,
                fullscreen: true,
                openFullscreen: false,
                closeOnEscape: true,
                overlay: true,
                overlayClose: false,
                overlayColor: 'rgba(0, 0, 0, 0.4)',
                timeout: false,
                timeoutProgressbar: false,
                pauseOnHover: false,
                timeoutProgressbarColor: 'rgba(255,255,255,0.5)',
                transitionIn: 'comingIn',
                transitionOut: 'comingOut',
                transitionInOverlay: 'fadeIn',
                transitionOutOverlay: 'fadeOut',
                onFullscreen: function(){},
                onResize: function(){},
                onOpening: function(){},
                onOpened: function(){
                    obj.Validator();
                },
                onClosing: function(){
                    $('#formFile')[0].reset();
                    $("#formFile").data('bootstrapValidator').destroy();
                },
                onClosed: function(){}
            });
            var html = '<div class="box-body"style="margin:5px 0 -10px 0">'
                +'<form class="form-horizontal" id="formFile" method="post" enctype="multipart/form-data">'
                +		'<div class="form-group hide">'
                +				'<label for="name" class="col-sm-2 control-label  no-pr text-muted">keyId</label>'
                +			'<div class="col-sm-10">'
                +				'<input type="text" class="form-control"   name="keyId" placeholder="">'
                +			'</div>'
                +		'</div>'
                +		'<div class="form-group hide">'
                +			'<label class="col-sm-2 control-label no-pr text-muted">类型&nbsp;&nbsp;</label>'
                +			'<div class="col-sm-10">'
                +				'<input type="text" class="easyui-validatebox form-control validatebox-text validatebox-invalid" name="keyType"  readonly ">'
                +			'</div>'
                +		'</div>'
                    +'<input type="hidden" name="type" value="">'
    /*            +		'<div class="form-group ">'
                +			'<label class="col-sm-2 control-label no-pr text-muted">名称&nbsp;&nbsp;</label>'
                +			'<div class="col-sm-10">'
                +				'<input type="text" class="easyui-validatebox form-control validatebox-text validatebox-invalid" name="name" id="name" readonly ">'
                +			'</div>'
                +		'</div>'
                +		'<div class="form-group ">'
                +			'<label class="col-sm-2 control-label no-pr text-muted">编号&nbsp;&nbsp;</label>'
                +			'<div class="col-sm-10">'
                +				'<input type="text" class="easyui-validatebox form-control validatebox-text validatebox-invalid" name="number" id="number" readonly ">'
                +			'</div>'
                +		'</div>'*/
                +		'<div class="form-group ">'
                +			'<label class="col-sm-2  control-label no-pr text-muted">文件类型<span class="text-red"> *</span></label>'
                +			'<div class="col-sm-10">'
                +				'<select class="form-control pull-right" style="width: 100%;" id="fileType" name="fileType"> </select>'
                +			'</div>'
                +		'</div>'
                +		'<div class="form-group ">'
                +			'<label class="col-sm-2  control-label no-pr text-muted">起始时间&nbsp;&nbsp;</label>'
                +	 		'<div class="col-sm-10">'
                +				'<input type="text" class="form-control" id="fileDateStart" name="fileDateStart">'
                +			'</div>'
                +		'</div>'
                +		'<div class="form-group">'
                +			'<label class="col-sm-2  control-label no-pr text-muted">到期时间&nbsp;&nbsp;</label>'
                +			'<div class="col-sm-10">'
                +				'<input type="text" class="form-control" id="fileDateEnd" name="fileDateEnd">'
                +			'</div>'
                +		'</div>'
/*                +		'<div class="form-group" >'
                +			'<label class="col-md-2 control-label no-pr  text-muted">原文件</label>'
                +			'<div class="col-md-10" id="oldFileInfo">'
                +			'</div>'
                +		'</div>'*/
                +		'<div class="form-group" >'
                +			'<label class="col-md-2 control-label no-pr  text-muted">文件<span class="text-red"> *</span></label>'
                +			'<div class="col-md-10" id="fileinfo">'
                +				'<input type="file" class="file" multiple name="files" id="files">'
                +			'</div>'
                +		'</div>'
                +      '<div class="form-group upload-img" style="position: fixed;width: 100%;top: 0;left: 0;height: 100%;z-index: 9999;background: rgba(255, 255, 255, 0.5);display: none">'
                +		    '<div style="text-align: center">'
                +				'<img src="../images/loading.gif" style="position: absolute;margin-top: -110px;top: 50%;left: 50%;margin-left: -88px;">'
                +			'</div>'
                +		'</div>'
                +	 	'<div class="form-group ">'
                +			'<label class="col-sm-2  control-label no-pr text-muted">备注&nbsp;&nbsp;</label>'
                +			'<div class="col-sm-10">'
                +				'<textarea class="easyui-validatebox form-control validatebox-text validatebox-invalid" name="remark" id="remark"></textarea>'
                +			'</div>'
                +		'</div>'
                +		'<div class="box-footer text-right"style="padding-right:0">'
                +				'<button data-iziModal-close class="btn btn-default" style="margin-right:5px">取消</button>'
                +				'<button name="save"data-loading-text="保存中..."  class="btn btn-info submit">保存</button>'
                +		'</div>'
                +	'</form>'
                +	'</div>';


            $obj.find(".iziModal-content").html(html);
            if(opts.keyId!=null){
                $obj.find('input[name="keyId"]').val(opts.keyId);
            }

            if(opts.keyType!=null){
                $obj.find('input[name="keyType"]').val(opts.keyType);
            }

            $obj.find('input[name="type"]').val(opts.type);
            $obj.find("select[name='fileType']").val(null).trigger("changer");
            $obj.find("select[name='fileType']").select2({language:"zh-CN",placeholder: "请选择文件类型",allowClear: true});

            this.FileType();

            $("#fileDateStart").datetimepicker({
                autoclose: true,
                todayHighlight:true,
                language:'zh-CN',
                format:'yyyy-mm-dd',
                minView:2,
                todayBtn:true,
            }).on('hide',function(e) {
                $('#formFile').data('bootstrapValidator').updateStatus('fileDateStart', 'NOT_VALIDATED',null).validateField('fileDateStart');
            });
            $("#fileDateEnd").datetimepicker({
                autoclose: true,
                todayHighlight:true,
                language:'zh-CN',
                format:'yyyy-mm-dd',
                minView:2,
                todayBtn:true,
            }).on('hide',function(e) {
                $('#formFile').data('bootstrapValidator').updateStatus('fileDateEnd', 'NOT_VALIDATED',null).validateField('fileDateEnd');
            });

            $('#files').fileinput({
                language: 'zh', //设置语言
                enctype: 'multipart/form-data',
                showUpload: false, //是否显示上传按钮
                showCaption: false,//是否显示标题
                browseClass: "btn btn-info", //按钮样式
                msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！"
            });

            this.eventBind = function(){
                var self = this;
                //必须先解绑再绑定事件，否则多次执行后会多次触发
                $obj.off('click','button[name="save"]').on('click','button[name="save"]',function(){
                    $('#formFile').bootstrapValidator('validate');
                    if(($("#fileDateEnd").val() == "" && $("#fileDateEnd").val()=="") || ($("#fileDateEnd").val() > $("#fileDateStart").val())){
                        if($('#formFile').data('bootstrapValidator').isValid()){
                            $("#save").button('loading');
                            var formData = new FormData($("#formFile")[0]);
                            $.ajax({
                                type : "POST",
                                url: opts.root+"/fileUpload/fileUpload",
                                data :formData,//整个表单提交
                                dataType : "json",
                                async: true,
                                cache: false,
                                contentType: false,
                                processData: false,
                                beforeSend: function(){
                                    $(".upload-img").css("display","block");
                                },
                                success : function(data) {
                                    $("#save").button('reset');
                                    try {
                                        if (data.ret == 200) {
                                            $obj.iziModal('close');
                                            new $.flavr({content:'保存成功',closeOverlay:true,closeEsc:true,autoclose:true,timeout:1500,buttons:[{text:'确定',style:'success'}]});
                                        } else {
                                            new $.flavr({content:'保存失败',closeOverlay:true,closeEsc:true,autoclose:true,timeout:1500,buttons:[{text:'确定',style:'danger'}]});
                                        }
                                    } catch (error) {
                                        new $.flavr({content:data.msg,closeOverlay:true,closeEsc:true,autoclose:true,timeout:1500,buttons:[{text:'确定',style:'warning'}]});
                                    }
                                },
                                failure : function() {
                                    $(".upload-img").css("display","none");
                                    new $.flavr({content:"保存失败",closeOverlay:true,closeEsc:true,autoclose:true,timeout:1500,buttons:[{text:'确定',style:'danger'}]});
                                }
                            });
                        }
                    }else{
                        new $.flavr({content:'到期时间必须晚于起始时间',closeOverlay:true,closeEsc:true,autoclose:true,timeout:1500,buttons:[{text:'确定',style:'danger'}]});
                    }
                });
            }
        }

        this.init = function (){
            this.filling(opts,this);
            this.eventBind();
        }

        this.init();

    }


    $.fn.fileUpload = function(parameter,callback){
        if(typeof parameter == 'function'){//重载
            callback = parameter;
            parameter = {};
        }else{
            parameter = parameter || {};
            callback = callback || function(){};
        }
        var options = $.extend({},defaults,parameter);
        callback(new FileUpload(this, options));
    };


})(jQuery, window,document);